package com.jl.driver.vritual.ternimal;

import java.io.*;

public class MBUF
{
	private byte[] _B = new byte[1024];
	private int _P = 0;
	private int _H = 0;
	private int _T = 0;

	public MBUF()
	{
	}

	synchronized public int read(byte[] buf, int offset, int length)
	{
		//System.out.println("H|P|T:" + _H + "|" + _P + "|" + _T);
		if ((_T-_P)<length)
			length = _T-_P;
		System.arraycopy(_B, _P, buf, offset, length);
		_P += length;
		if (_P==_T)
		{
			_P = _T = _H = 0;
		}
		return length;
	}

	synchronized public byte[] _spy()
	{
		byte[] buf = null;
		int len = _T-_H;
		if (len>0)
		{
			buf = new byte[len];
			System.arraycopy(_B, _H, buf, 0, len);
			_H = _T;
		}
		return buf;
	}

	synchronized public int fill(InputStream ins)
	{
		if (ins!=null)
		{
			try
			{
				_T += ins.read(_B, _T, _B.length-_T);
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
				return -1;
			}
		}
		return 0;
	}

	synchronized public int available()
	{
		return _T-_P;
	}

}
